{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.layui-form-item .layui-input-inline.end-time{
		float: none;
	}
	.time-label{
		display: inline-block;
		line-height: 30px;
		height: 30px;
		padding: 0 15px;
		border-radius: 2px;
		border: 1px solid #e9e9e9;
		background: #f7f7f7;
		font-size: 12px;
		vertical-align: middle;
		opacity: 1;
		margin: 4px 8px 4px 0;
		cursor: pointer;
		position: relative;
	}
	.time-label span{
		vertical-align: middle;
	}
	.time-label i{
		font-size: 12px;
		position: absolute;
		top: -8px;
		right: -8px;
		width: 16px;
		height: 16px;
		line-height: 16px;
		text-align: center;
		color: #fff;
		-webkit-border-radius: 10px;
		-moz-border-radius: 10px;
		border-radius: 10px;
		background: rgba(0, 0, 0, 0.3);
	}
	.seckill-box .layui-table-col-special{
		padding: 5px 0 !important;
	}
	.layui-table-body{max-height: 480px !important;}
	.goods-title{display: flex;align-items: center;}
	.goods-title .goods-img{display: flex;align-items: center;justify-content: center;width: 55px;height: 55px;margin-right: 5px;}
	.goods-title .goods-img img{max-height: 100%;max-width: 100%;}
	.goods-title .goods-name{flex: 1;line-height: 1.6;}
</style>
{/block}
{block name="main"}
<div class="layui-form ns-form">
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动名称：</label>
		<div class="layui-input-block">
			<input type="text" name="seckill_name" lay-verify="required" autocomplete="off" class="layui-input ns-len-long">
		</div>
		<div class="ns-word-aux">
			<p>活动名称将显示在列表中展示，方便商家管理使用</p>
		</div>
	</div>

	<div class="layui-form-item layui-form-text">
		<label class="layui-form-label">备注：</label>
		<div class="layui-input-block">
			<textarea name="remark" class="layui-textarea ns-len-long"></textarea>
		</div>
		<div class="ns-word-aux">
			<p>备注是商家对秒杀的补充说明文字，非必填选项</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动时间：</label>
		<div class="layui-inline">
			<div class="layui-input-inline">
				<input type="text" id="start_time" name="start_time" lay-verify="required" class="layui-input ns-len-mid" autocomplete="off" readonly>
				<i class="ns-calendar"></i>
			</div>
			<span class="layui-form-mid">-</span>
			<div class="layui-input-inline end-time">
				<input type="text" id="end_time" name="end_time" lay-verify="required|time" class="layui-input ns-len-mid" autocomplete="off" readonly>
				<i class="ns-calendar"></i>
			</div>
		</div>
		<div class="ns-word-aux">
			<p>商品只会在活动时间段内的指定场次进行展示</p>
		</div>
	</div>

	<div class="seckill-goods-list">
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>参与场次：</label>
			<div class="layui-input-inline">
				<div class="layui-input-inline ns-len-long time-label-list">
					<a href="javascript:addSeckillTime();" class="ns-text-color js-add-time">选择场次</a>
					<ul></ul>
				</div>
			</div>
		</div>
	</div>
	<div class="layui-form-item goods_list">
		<label class="layui-form-label"><span class="required">*</span>商品选择：</label>
		<div class="layui-input-block">
			<table id="selected_goods_list" lay-filter="selected_goods_list"></table>
			<button class="layui-btn ns-bg-color" onclick="addGoods()">选择商品</button>
		</div>
	</div>
	<input type="hidden" name="seckill_time_id">
	<div class="ns-form-row">
		<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
	</div>
</div>


<!--选择场次弹出-->
<script type="text/html" id="seckillTime">
	<div class="seckill-box">
		<div class="ns-single-filter-box">
			<button class="layui-btn ns-bg-color" onclick="clickAddTime()">添加秒杀场次</button>
		</div>
		<table id="seckill_time_list" lay-filter="seckill_time_list"></table>
	</div>
</script>


<!-- 操作 -->
<script type="text/html" id="timeoperation">
	<div class="ns-table-btn" style="text-align: center">
		<a class="layui-btn" lay-event="edit">编辑</a>
		<a class="layui-btn" lay-event="delete">删除</a>
	</div>
</script>


<script type="text/html" id="timecheckbox">
	{{# if (d.is_select == 1){ }}
	<input type="checkbox" data="" data-name="{{ d.name }}" data-time-start="{{d.seckill_start_time}}" checked  data-time-end="{{d.seckill_end_time}}" data-time-id="{{d.id}}" class="time-select" lay-skin="primary" lay-filter="goods_checkbox">
	{{# }else{ }}
	<input type="checkbox" data="" data-name="{{ d.name }}" data-time-start="{{d.seckill_start_time}}"  data-time-end="{{d.seckill_end_time}}" data-time-id="{{d.id}}" class="time-select" lay-skin="primary" lay-filter="goods_checkbox">
	{{# } }}
</script>

<script type="text/html" id="toolbarOperation">
	<button class="layui-btn layui-btn-primary" lay-event="seckill-purchase">限购</button>
	<button class="layui-btn layui-btn-primary" lay-event="seckill-price">秒杀价</button>
	<button class="layui-btn layui-btn-primary" lay-event="seckill-stock">秒杀库存</button>
</script>

<!-- 操作 -->
<script type="text/html" id="operation">
	<div class="ns-table-btn">
		<a class="layui-btn" onclick="delGoods(this,{{d.sku_id}})">删除</a>
	</div>
</script>

<!-- 价格设置 -->
<script type="text/html" id="seckillPrice">
	<input type="number" class="layui-input ns-len-input seckill_price" value="{{d.seckill_price}}" onchange="setGoodsSku('seckill_price', {{d.sku_id}}, this)"  min="0.00"/>
</script>

<!-- 库存设置 -->
<script type="text/html" id="seckillStock">
	<input type="number" class="layui-input ns-len-input seckill_stock" value="{{d.seckill_stock}}" onchange="setGoodsSku('seckill_stock', {{d.sku_id}}, this)"  min="0.00"/>
</script>

<!-- 限购设置 -->
<script type="text/html" id="maxBuy">
	<input type="number" class="layui-input ns-len-input max_buy" value="{{d.max_buy}}" onchange="setGoodsSku('max_buy', {{d.sku_id}}, this)"  min="0"/>
</script>

<!-- 添加场次 -->
<script type="text/html" id="addTime">
	<div class="layui-form">
		<div class="layui-form-item ns-len-mid">
			<label class="layui-form-label"><span class="required">*</span>秒杀场次名称：</label>
			<div class="layui-input-block">
				{{# if(d.name){ }}
				<input type="text" id="add_time_name" value="{{d.name}}" lay-verify="required" autocomplete="off" class="layui-input ns-len-mid">
				{{# }else{ }}
				<input type="text" id="add_time_name" value="" lay-verify="required" autocomplete="off" class="layui-input ns-len-mid">
				{{# } }}
			</div>
		</div>
		<div class="layui-form-item ">
			<div class="layui-inline">
				<label class="layui-form-label"><span class="required">*</span>秒杀时间段：</label>
				<div class="layui-inline">
					<div class="layui-input-inline">
						<input type="text" id="add_start_time" value="{{d.seckill_start_time_show}}" lay-verify="required" class="layui-input">
						<i class="ns-calendar"></i>
					</div>
					<span class="layui-form-mid">-</span>
					<div class="layui-input-inline">
						<input type="text" id="add_end_time" value="{{d.seckill_end_time_show}}" lay-verify="required" class="layui-input">
						<i class="ns-calendar"></i>
					</div>
				</div>
			</div>
		</div>
	</div>
</script>

{/block}
{block name="script" }
<script>
	var goods_id = [],selectedGoodsId = [], sku_list = [], selectedTimeId = [], time_list = [],
		form,laytpl,laydate,
		timeTable;
	layui.use(['form', 'laydate', 'laytpl'], function() {
		form = layui.form;
		laytpl = layui.laytpl;
		laydate = layui.laydate;
		var repeat_flag = false, //防重复标识
			currentDate = new Date(),
			minDate = "";
		form.render();
		renderTable(sku_list); // 初始化表格

		currentDate.setDate(currentDate.getDate() + 30);
		laydate.render({
			elem: '#start_time', //指定元素
			type: 'datetime',
			value: new Date(),
			done: function(value) {
				minDate = value;
				reRender();
			}
		});
		//结束时间
		laydate.render({
			elem: '#end_time', //指定元素
			type: 'datetime',
			value: new Date(currentDate)
		});

		/**
		 * 重新渲染结束时间
		 * */
		function reRender() {
			$("#end_time").remove();
			$(".end-time").html('<input type="text" id="end_time" name="end_time" placeholder="请输入结束时间" lay-verify="required|time" class = "layui-input ns-len-mid" autocomplete="off"> ');
			laydate.render({
				elem: '#end_time',
				type: 'datetime',
				min: minDate
			});
		}

		/**
		 * 监听提交
		 */
		form.on('submit(save)', function(data) {

			if(verify()) {
				var goods_data = [];
				for (var i in sku_list) {
					var goods = {};
					goods.goods_id = sku_list[i]['goods_id'];
					if (goods_data.length == 0) {
						goods_data.push(goods);
					} else {
						$.each(goods_data, function (index, event) {
							if (goods_data.length == index + 1 && event.goods_id != goods.goods_id) {
								goods_data.push(goods);
							}
						})
					}
				}

				$.each(goods_data, function (i, e) {
					goods_data[i]['sku_list'] = [];
					$.each(sku_list, function (index, event) {
						if (event.goods_id == e.goods_id) {
							goods_data[i]['sku_list'].push(event);
						}
					})
				});

				data.field.goods_data = goods_data;
				data.field.goods_ids = selectedGoodsId;

				if (repeat_flag) return;
				repeat_flag = true;
				$.ajax({
					url: ns.url("seckill://shop/seckill/addGoods"),
					data: data.field,
					dataType: 'JSON',
					type: 'POST',
					success: function (res) {
						repeat_flag = false;

						if (res.code == 0) {
							layer.confirm('添加成功', {
								title: '操作提示',
								btn: ['返回列表', '继续添加'],
								closeBtn: 0,
								yes: function () {
									location.href = ns.url("seckill://shop/seckill/goodslist")
								},
								btn2: function () {
									location.href = ns.url("seckill://shop/seckill/addGoods");
								}
							});
						} else {
							layer.msg(res.message);
						}
					}
				});
			}
		});

		/**
		 * 表单验证
		 */
		form.verify({
			time: function(value) {
				var now_time = (new Date()).getTime();
				var start_time = (new Date($("#start_time").val())).getTime();
				var end_time = (new Date(value)).getTime();
				if (now_time > end_time) {
					return '结束时间不能小于当前时间!'
				}
				if (start_time > end_time) {
					return '结束时间不能小于开始时间!';
				}
			},

			seckilltime: function (value, item) {
				if (value == "" || value == 0) {
					return '请选择时间段';
				}
			}
		});

	});

	function verify(){
		if (sku_list.length == 0) {
			layer.msg('请选择商品', {icon: 5, anim: 6});
			return false;
		}

		if($('input[name="seckill_time_id"]').val() == ''){
			layer.msg('请选择场次', {icon: 5, anim: 6});
			return false;
		}

		for (var i in sku_list) {
			if(sku_list[i]['max_buy'] < 0) {
				layer.msg('商品限购不可小于0', {icon: 5, anim: 6});
				return false;
			}

			if(sku_list[i]['seckill_price'] <= 0) {
				layer.msg('秒杀价不可小于等于0', {icon: 5, anim: 6});
				return false;
			}
			if(sku_list[i]['seckill_stock'] > sku_list[i]['stock']) {
				layer.msg('秒杀库存不能大于商品库存', {icon: 5, anim: 6});
				return false;
			}
		}

		return true;
	}

	function delGoods(obj,id) {
		var goods_ids = [];
		for (let i = 0; i < sku_list.length; i++){
			if (sku_list[i].sku_id == parseInt(id)){
				sku_list.splice(i,1);
			}
		}
		for (let i = 0; i < sku_list.length; i++){
			goods_ids.push(sku_list[i].goods_id);
		}
		$(obj).parents("tr").remove();
		selectedGoodsId = goods_ids.toString();
	}

	// 表格渲染
	function renderTable(sku_list) {
		//展示已知数据
		table = new Table({
			elem: '#selected_goods_list',
			page: false,
			limit: Number.MAX_VALUE,
			cols: [
					[
					{
						width: "3%",
						type: 'checkbox',
						unresize: 'false'
					},
					{
					field: 'sku_name',
					title: '商品名称',
					width: '19%',
					unresize: 'false',
					templet: function(data) {
						var html = '';
						html += `
							<div class="goods-title">
								<div class="goods-img">
									<img src="${ns.img(data.sku_image)}" alt="">
								</div>
								<p class="ns-multi-line-hiding goods-name" data-goods_id="${data.goods_id}" data-sku_id="${data.sku_id}" title="${data.sku_name}">${data.sku_name}</p>
							</div>
						`;
						return html;
					}
				}, {
					field: 'price',
					title: '商品价格',
					unresize: 'false',
					align: 'left',
					width: '12%',
					templet: function(data) {
						return '<p class="ns-line-hiding" title="'+ data.price +'">￥<span>' + data.price +'</span></p>';
					}
				}, {
					field: 'stock',
					title: '库存',
					unresize: 'false',
					width: '10%',
					templet: function(data) {
						return '<p class="stock">' + data.stock +'</p>';
					}
				}, {
					field: 'max_buy',
					title: '<span title="限购(0为不限购)">限购(0为不限购)<span>',
					unresize: 'false',
					width: '17%',
					templet: '#maxBuy'

				}, {
					title: '<span title="秒杀价">秒杀价<span>',
					unresize: 'false',
					width: '13%',
					templet: '#seckillPrice'
				}, {
					title: '<span title="秒杀库存">秒杀库存<span>',
					unresize: 'false',
					width: '13%',
					templet: '#seckillStock'
				}, {
					title: '操作',
					toolbar: '#operation',
					width: '10%',
					unresize: 'false'
				}]
			],
			data: sku_list,
			toolbar: '#toolbarOperation'
		});
		table.toolbar(function(obj) {

			if (obj.data.length < 1) {
				layer.msg('请选择要操作的数据');
				return;
			}
			switch (obj.event) {
				case "seckill-purchase":
					editInput(0,obj);
					break;
				case "seckill-price":
					editInput(1,obj);
					break;
				case "seckill-stock":
					editInput(2,obj);
					break;
			}
		});
	}

	function editInput(textIndex=0,data) {
		var text = [{
			name: '限购',
			value: 'max_buy'
		},{
			name: '秒杀价',
			value: 'seckill_price'
		},{
			name: '秒杀库存',
			value: 'seckill_stock'
		}];
		layer.open({
			type: 1,
			title:"修改"+text[textIndex].name,
			area:['600px'],
			btn:["保存","返回"],
			content: `
			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>${text[textIndex].name}：</label>
				<div class="layui-input-block">
					<input type="text" name="bargain_edit_input" lay-verify="required" autocomplete="off" class="layui-input ns-len-mid" placeholder="请输入${text[textIndex].name}">
				</div>
			</div>
		`,
			yes: function(index, layero){
				var val = $("input[name='bargain_edit_input']").val();
				if (!val){
					layer.msg("请输入" + text[textIndex].name);
					return false;
				}
				data.data.forEach(function (item,index) {
					sku_list.forEach(function (skuItem,skuIndex) {
						if (item.sku_id == skuItem.sku_id){
							sku_list[skuIndex][text[textIndex].value] = val;
						}
					})
				});
				renderTable(sku_list);
				layer.closeAll();
			}
		});
	}

	/* 商品 */
	function addGoods(){

		goodsSelect(function (res) {
			if (!res.length) return false;
			for(var i=0;i<res.length;i++) {
				for (var k = 0; k < res[i].selected_sku_list.length; k++) {
					var item = res[i].selected_sku_list[k];
					item.seckill_price = item.price;
					item.max_buy = 1;
					item.seckill_stock = item.stock;
					goods_id.push(item.goods_id);
					sku_list.push(item);
				}
			}
			renderTable(sku_list);
			selectedGoodsId = goods_id;

		}, selectedGoodsId);
	}

	function setGoodsSku(type, sku_id, obj){
		$.each(sku_list, function (i, e) {
			if(sku_id == e.sku_id){
				sku_list[i][type] = $(obj).val();
			}
		})
	}

	function addSeckillTime(){
		layer.open({
			type: 1,
			title: "场次选择",
			area: ['900px', '620px'],
			btn: ['保存', '返回'],
			content: $('#seckillTime').html(),
			success:function(layero){
				renderTimeTable();
			},
			yes: function (index, layero) {
				var select_time_id = [];
				time_list = [];
				$('div[lay-id="seckill_time_list"] .time-select').each(function(i, e){
					if($(e).is(":checked")){

						let time = {};
						time.start_time = $(e).attr('data-time-start');
						time.end_time = $(e).attr('data-time-end');
						time.id = $(e).attr('data-time-id');
						time.name = $(e).attr('data-name');

						select_time_id.push($(e).attr('data-time-id'));
						time_list.push(time);
					}
				});
				$('input[name="seckill_time_id"]').val(select_time_id.toString());
				refreshTimeList(time_list);
				layer.closeAll();
			}
		});
	}

	function refreshTimeList(time_list){
		var html = '';

		for (let i in time_list){
			let start_time = transformSeckillTime(time_list[i]['start_time']);
			let end_time = transformSeckillTime(time_list[i]['end_time']);
			let name = time_list[i]['name'];
			let id = time_list[i]['id'];
			html += `
				<li class="time-label" title="${start_time} - ${end_time}">
				   <span>${name}</span>
				   <i class="layui-icon layui-icon-close" onclick="delTime(${id}, this)"></i>
				</li>
			`;
		}
		$('.time-label-list ul').html(html);

	}

	function delTime(id, obj) {
		time_list.splice(time_list.indexOf(id),1);
		let time = [];
		for (let i in time_list){
			if(time_list[i]['id'] != id){
				time.push(time_list[i]['id']);
			}
		}
		$('input[name="seckill_time_id"]').val(time.toString());
		$(obj).parents('li').remove();
	}

	//场次渲染
	function renderTimeTable(){
		$.ajax({
			url: ns.url("seckill://shop/seckill/lists"),
			dataType: 'JSON',
			type: 'POST',
			success: function (res) {
				if (res.code < 0){
					layer.msg(res.message);
					return false;
				}

				var time_data = res.data;
				for (let i in time_data){
					time_data[i]['is_select'] = 0;
					for (let j in time_list){
						if(time_list[j]['id'] == time_data[i]['id']){
							time_data[i]['is_select'] = 1;
						}
					}
				}
				timeTable = new Table({
					elem: '#seckill_time_list',
					page: false,
					height: 380,
					limit:  Number.MAX_VALUE,
					cols: [
						[{
							unresize: 'false',
							width: '10%',
							align: 'left',
							templet: '#timecheckbox'
						},{
							field:'name',
							title:'场次名称',
							unresize: 'false',
							align: 'left',
							width: '26%'
						}, {
							field:'seckill_start_time_show',
							title:'开始时间',
							unresize: 'false',
							width: '25%'
						}, {
							field:'seckill_end_time_show',
							title:'结束时间',
							unresize: 'false',
							width: '25%'
						}, {
							toolbar: '#timeoperation',
							title:'操作',
							unresize: 'false',
							align: 'left',
							width: '14%'
						}]
					],
					data: time_data
				});

				timeTable.tool(function(obj) {
					var data = obj.data;
					switch (obj.event) {
						case 'delete':
							deleteSeckilTime(obj);
							break;
						case 'edit':
							clickAddTime(data);
							break;
					}

				});
			}
		});

	}

	function transformSeckillTime(time)
	{
		time = parseFloat(time);
		var hour = parseInt(time / 3600);
		var minute = parseInt((time % 3600 ) / 60);
		var second = parseInt(time % 60);

		if(hour < 10) hour = '0'+hour;
		if(minute < 10) minute = '0'+minute;
		if(second < 10) second = '0'+second;

		return hour+':'+minute+':'+second;
	}

	//添加场次
	function clickAddTime(indent = "") {
		var title = indent  ? "场次编辑" : "场次添加";
		var url = indent ? ns.url("seckill://shop/seckill/edit") : ns.url("seckill://shop/seckill/add");
		var data = indent ? indent : {};
		laytpl($('#addTime').html()).render(data, function(html){
			var index= layer.open({
				type: 1,
				title: title,
				area: ['700px', '300px'],
				btn: ['保存', '返回'],
				content: html,
				yes: function (index, layero) {
					var data = {};
					if (indent){
						data.id = indent.id;
					}
					data.name = $('#add_time_name').val();
					if (!data.name){
						layer.msg("秒杀场次名称不能为空");
						return false;
					}
					if (!$('#add_start_time').val()){
						layer.msg("开始时间不能为空");
						return false;
					}
					if (!$('#add_end_time').val()){
						layer.msg("结束时间不能为空");
						return false;
					}
					data.start_hour = $('#add_start_time').val().split(":")[0];
					data.start_minute = $('#add_start_time').val().split(":")[1];
					data.start_second = $('#add_start_time').val().split(":")[2];

					data.end_hour = $('#add_end_time').val().split(":")[0];
					data.end_minute = $('#add_end_time').val().split(":")[1];
					data.end_second = $('#add_end_time').val().split(":")[2];

					if (repeat_flag) return;
					repeat_flag = true;
					$.ajax({
						url: url,
						data: data,
						dataType: 'JSON',
						type: 'POST',
						success: function (res) {
							repeat_flag = false;
							if (res.code == 0){
								renderTimeTable();
								layer.msg(res.message,{},function(){
									layer.close(index);
								});
							}else{
								layer.msg(res.message);
							}

						}
					});
				}
			});
			laydate.render({
				elem: '#add_end_time',
				type: 'time'
			});
			laydate.render({
				elem: '#add_start_time',
				type: 'time'
			});
		});
	}

	//删除秒杀时段
	function deleteSeckilTime (event){
		var data = {id:event.data.id};
		$.ajax({
			url: ns.url("seckill://shop/seckill/delete"),
			data: data,
			dataType: 'JSON',
			type: 'POST',
			success: function (res) {
				layer.msg(res.message);
				if (res.code == 0){
					$(event.tr).remove();
				}

			}
		});
	}

	function back() {
		location.href = ns.url("seckill://shop/seckill/goodslist");
	}
</script>
{/block}